package com.quzhi.sys.controller.warehouseController;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quzhi.common.code.Code;
import com.quzhi.common.Result;
import com.quzhi.sys.dto.WarehouseDto;
import com.quzhi.sys.entity.Inventory;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.entity.Warehouse;
import com.quzhi.sys.service.impl.InventoryServiceImpl;
import com.quzhi.sys.service.impl.WarehouseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器 cangkku
 * </p>
 *
 * @author Xibing
 * @since 2024-07-23
 */
@Slf4j
@RestController
@RequestMapping("/sys/warehouse")
public class WarehouseController {

    @Autowired
    private WarehouseServiceImpl warehouseService;

    @Autowired
    private InventoryServiceImpl inventoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/list")
    public Result<?> getWarehouseList(
            @RequestParam(value = "warehouseName", required = false) String warehouseName,
            @RequestParam(value = "pageNo") Long pageNo,
            @RequestParam(value = "pageSize") Long pageSize
    ) {
        LambdaQueryWrapper<Warehouse> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(warehouseName), Warehouse::getWarehouseName, warehouseName);
        Page<Warehouse> infoPage = new Page<>(pageNo, pageSize);

        warehouseService.page(infoPage, wrapper);

        List<Warehouse> records = infoPage.getRecords();
        List<WarehouseDto> warehouseDtos = new ArrayList<>();
        for (Warehouse record : records) {
            WarehouseDto warehouseDto = new WarehouseDto();
            BeanUtils.copyProperties(record, warehouseDto, "records");

            // 查询商品计算实例
            LambdaQueryWrapper<Inventory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Inventory::getWarehouseId, warehouseDto.getId());
            Integer count = Math.toIntExact(inventoryService.count(lambdaQueryWrapper));
            warehouseDto.setInventoryNumber(count);
            warehouseDtos.add(warehouseDto);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("rows", warehouseDtos);
        data.put("total", infoPage.getTotal());
        return Result.success(data);
    }

    @GetMapping("/{id}")
    public Result<?> getWarehouseById(@PathVariable("id") String id) {
        Warehouse warehouse = warehouseService.getById(id);

        return Result.success(warehouse);
    }

    // 查询所有仓库名称
    @GetMapping("/select")
    public Result<?> getAllProductNameAndId() {
        List<Warehouse> list = warehouseService.list();

        List<Map<String, String>> reList = new ArrayList<>();

        for (Warehouse warehouse : list) {
            Map<String, String> house = new HashMap<>();
            house.put("id", warehouse.getId());
            house.put("warehouseName", warehouse.getWarehouseName());
            reList.add(house);
        }

        return Result.success(reList);
    }

    @PostMapping
    public Result<?> addWarehouse(@RequestBody Warehouse warehouse) {
        LambdaQueryWrapper<Warehouse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Warehouse::getWarehouseName, warehouse.getWarehouseName());

        Warehouse one = warehouseService.getOne(wrapper);

        // 如果仓库存在则不允许添加
        if (one != null) return Result.fail(20002, "该仓库已存在");

        // 添加仓库
        warehouse.setId(UUID.randomUUID().toString());
        warehouse.setCreateTime(LocalDateTime.now());
        warehouse.setUpdateTime(LocalDateTime.now());
        warehouseService.save(warehouse);

        return Result.success("添加成功");
    }

    @PutMapping
    public Result<?> updateWareHouse(@RequestBody Warehouse warehouse) {
        // 只能修改仓库名称
        Warehouse oldWarehouse = warehouseService.getById(warehouse);
        oldWarehouse.setWarehouseName(warehouse.getWarehouseName());
        oldWarehouse.setUpdateTime(LocalDateTime.now());

        warehouseService.updateById(oldWarehouse);

        return Result.success("更新成功");
    }


    // 删除仓库
    @DeleteMapping("/{id}")
    public Result<?> deleteWareHouse(@PathVariable("id") String id, @RequestBody String qz_token) {
        // 查询当前用户的权限是否可以删除仓库
        Object obj = redisTemplate.opsForValue().get(qz_token);
        if (obj != null) {
            // 将数据转成json数据
            User loginUser = JSON.parseObject(JSON.toJSONString(obj), User.class);
            // 删除仓库
            String role = loginUser.getRole();
            if (role.equals("admin")) {
                // 更具仓库Id查询序列号是否有库存
                LambdaQueryWrapper<Inventory> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Inventory::getWarehouseId, id);
                long count = inventoryService.count(wrapper);
                if(count > 0){
                    return Result.fail(Code.FAIL_CODE, "该仓库有"+count+"个库存，请先调拨库存");
                }
                // 权限足够可以删除
                warehouseService.removeById(id);
                return Result.success("删除成功");
            } else {
                return Result.fail(20002, "你没有权限执行此操作");
            }
        } else {
            return Result.fail(20002, "删除失败");
        }
    }
}
